const BaseMonitor = require('./base-monitor');

class LedMonitor extends BaseMonitor {
  constructor(deviceId, mqttConnector) {
    super(deviceId, mqttConnector);
    this.controlTopic = 'device/led';
    this.stateTopic = 'device/led/state';
    this.state = 'off';
    this.status = 'normal';

    // 注册消息处理
    this.onMessage(this.stateTopic, this.handleStateMessage.bind(this));
  }

  // 初始化
  async init() {
    await this.subscribe(this.stateTopic);
    console.log('LED灯监控模块已初始化');
  }

  // 处理状态消息
  handleStateMessage(message) {
    try {
      // 只处理JSON格式消息（已在mqtt-connector中解析）
      if (typeof message === 'object' && message.type === 'sensor-data' && message.data) {
        this.state = message.data.value;
        this.status = message.data.status || 'normal';

        console.log(`[LED灯] 设备ID: ${message.deviceId}, 当前状态: ${this.state === 'on' ? '开启' : '关闭'}, 状态: ${this.status}`);

        // 触发状态更新事件（如果有监听器）
        if (this.onUpdate) {
          this.onUpdate({
            deviceId: message.deviceId,
            timestamp: message.timestamp,
            state: this.state,
            status: this.status
          });
        }
      } else {
        console.log(`无效的LED状态消息格式: ${JSON.stringify(message)}`);
      }
    } catch (error) {
      console.error(`处理LED状态消息错误: ${error.message}`);
    }
  }

  // 控制LED灯
  async control(state) {
    try {
      const command = {
        deviceId: this.deviceId,
        timestamp: Date.now(),
        type: 'control-command',
        command: {
          action: state === 'on' ? 'turn-on' : 'turn-off'
        }
      };

      await this.publish(this.controlTopic, JSON.stringify(command));
      console.log(`已发送LED${state === 'on' ? '开启' : '关闭'}命令`);
      return true;
    } catch (error) {
      console.error(`发送LED控制命令失败: ${error.message}`);
      return false;
    }
  }

  // 切换LED状态
  async toggle() {
    return this.control(this.state === 'on' ? 'off' : 'on');
  }

  // 获取当前LED状态
  getCurrentState() {
    return {
      state: this.state,
      status: this.status
    };
  }
}

module.exports = LedMonitor;